package com.teacher.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teacher.common.CommonResult;
import com.teacher.mapper.TermMapper;
import com.teacher.pojo.dto.practicegrades.PracticeGradesGetDto;
import com.teacher.pojo.entity.PracticeGrades;
import com.teacher.mapper.PracticeGradesMapper;
import com.teacher.pojo.excel.PracticeGradesExcel;
import com.teacher.pojo.vo.practicegrades.PracticeGradesGetVo;
import com.teacher.service.IPerStudentService;
import com.teacher.service.IPracticeGradesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacher.service.listener.ExcelPracticeGradesListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 * 实习成绩 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2021-07-30
 */
@Service
public class PracticeGradesServiceImpl extends ServiceImpl<PracticeGradesMapper, PracticeGrades> implements IPracticeGradesService {

    @Autowired
    private TermMapper termMapper;

    @Autowired
    private IPerStudentService iPerStudentService;

    /**
     * 查询实习成绩
     *
     * @param dto
     * @return
     */
    @Override
    public CommonResult<IPage<PracticeGradesGetVo>> getPage(PracticeGradesGetDto dto) {
        Page<PracticeGradesGetVo> page = new Page<>(dto.getCurrentPage(), dto.getPageSize());
        if (dto.getTermId() == null) {
            dto.setTermId(termMapper.getCurrentTerm());
        }
        IPage<PracticeGradesGetVo> iPage = baseMapper.getPage(page, dto);
        return CommonResult.success(iPage);
    }

    /**
     * 导入实习成绩
     *
     * @param file
     * @return
     */
    @Override
    public CommonResult<String> upload(MultipartFile file) {
        Long termId = termMapper.getCurrentTerm();
        try {
            EasyExcel.read(file.getInputStream(), PracticeGradesExcel.class,
                    new ExcelPracticeGradesListener(termId, this, iPerStudentService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("上传失败");
        }
        return CommonResult.success("导入成功");
    }
}
